
package liwei;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * @author LiWei
 * a pop out frame that can convert a specific number system to another by inputing both the original system and
 * the aiming system.After tapped the ENTER key,we can get the result.
 *	进行进制转换的弹出面板，输入原始进制、目标进制以及原串，得到转换后的串
 */
public class ConversionFrame extends JFrame
{
	/**
	 * this is the testing main method I wrote to test whether this works,which turned out good
	 * @param args
	 */
	public static void main(String[] args)
	{
		ConversionFrame aConversionFrame = new ConversionFrame();
		aConversionFrame.setVisible(true);
	}
	public ConversionFrame()
	{
		setSize(200, 200);
		JPanel aPanel = new JPanel();
		add(aPanel);
		final JTextField fromTextField = new JTextField("请输入原始进制");
		//按下鼠标就把输入框清空
		//set the text field empty after tapped by the mouse
		fromTextField.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent e)
			{
				fromTextField.setText("");
			}
		});
		final JTextField toTextField = new JTextField("请输入目标进制");
		toTextField.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent e)
			{
				toTextField.setText("");
			}
		});
		final JTextField numTextField = new JTextField("请输入要转化的数后，按回车键");
		numTextField.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent e)
			{
				numTextField.setText("");
			}
		});
		final JLabel resultLabel = new JLabel("结果");
		aPanel.add(fromTextField);
		aPanel.add(toTextField);
		aPanel.add(numTextField);
		aPanel.add(resultLabel);
		//the movement when the ENTER is pressed
		numTextField.addActionListener(new ActionListener()
		{
			//当用户按下回车键时的动作，提取从什么进制转换到什么进制以及要被转换的数
			@Override 
			public void actionPerformed(ActionEvent arg0)
			{
				//first I extract the the number systems needed and then the original number string
				//at last I used the system method in Integer Class to complete this converting function
				String fromString = fromTextField.getText();
				String toString = toTextField.getText();
				String numString = numTextField.getText();
				resultLabel.setText(convertor(numString, Integer.parseInt(fromString),Integer.parseInt(toString)));
			}
		});
	}
	/**
	 * 	使用Integer类自带的函数来完成进制转换
	 * using the method from Integer class to convert the numbers 
	 * @param number the number to be converted
	 * @param from the original number system
	 * @param to the aim number system
	 * @return the converted result
	 */
	public String convertor(String number,int from,int to)
	{
		Integer num = Integer.parseInt(number, from);
		return Integer.toString(num, to);
	}
}
